package com.example.network.socket

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.example.network.databinding.FragmentWebSocketBinding
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket

class WebSocketFragment : Fragment() {
    private lateinit var webSocketListener: WebSocketListener
    private lateinit var viewModel: WebSocketViewModel
    private val okHttpClient = OkHttpClient()
    private var webSocket: WebSocket? = null

    private var _binding: FragmentWebSocketBinding? = null
    private val binding get() = _binding!!

    private val statusTV get() = binding.statusTV
    private val messageTV get() = binding.messageTV
    private val messageET get() = binding.messageET
    private val connectButton get() = binding.connectButton
    private val disconnectButton get() = binding.disconnectButton
    private val sendMessageButton get() = binding.sendButton

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this)[WebSocketViewModel::class.java]
        webSocketListener = WebSocketListener(viewModel)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentWebSocketBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel.socketStatus.observe(viewLifecycleOwner) {
            statusTV.text = if (it) "Connected" else "Disconnected"
        }

        var text = ""
        viewModel.messages.observe(viewLifecycleOwner) {
            text += "${if (it.first) "You: " else "Other: "} ${it.second}\n"

            messageTV.text = text
        }


        connectButton.setOnClickListener {
            webSocket = okHttpClient.newWebSocket(createRequest(), webSocketListener)
        }
        disconnectButton.setOnClickListener {
            webSocket?.close(1000, "Canceled manually.")
        }
        sendMessageButton.setOnClickListener {
            val textSent = messageET.text.toString()
            webSocket?.send(textSent)
            messageET.text.clear()
            viewModel.addMessage(Pair(true, textSent))
        }
    }

    private fun createRequest(): Request {
        val websocketURL = "wss://echo.websocket.org"

        return Request.Builder()
            .url(websocketURL)
            .build()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        okHttpClient.dispatcher.executorService.shutdown()
    }
}